from flask import jsonify, request, Response, send_file, g, session
from . import lessonPlan_bp
from docx import Document
from models import LessonPlan
import openai
import re
openai.api_key ="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"
import io

@lessonPlan_bp.route('/')
def index():
    return jsonify(u"this is lessonPlan url prefix")

@lessonPlan_bp.route('/generate',methods=["POST"])
def generate_lessonPlan():
    main_knowledge = request.form.get('main_knowledge')
    min_age = request.form.get('min_age')
    max_age = request.form.get('max_age')
    class_hour_count = request.form.get('class_hour_count')
    other_requirements = request.form.get('other_requirements')
    # messages = [
    #     {'role': 'system', 'content': 'Please generate an appropriate lesson plan based on the input provided.'},
    #     {'role': 'user', 'content': f'Main Knowledge: {main_knowledge}'},
    #     {'role': 'user', 'content': f'Students Age: {min_age} to {max_age}'},
    #     {'role': 'user', 'content': f'Class Hour Count: {class_hour_count}'},
    #     {'role': 'user', 'content': f'Other Requirements: {other_requirements}'},
    #     {'role': 'system', 'content': 'Please start by generating the teaching objectives section.'},

    #     {'role': 'system', 'content': 'Next, please describe the teaching methods.'},
    #     {'role': 'system', 'content': 'Then, please identify the key points and difficulties of the teaching.'},
    #     {'role': 'system', 'content': 'Finally, please elaborate on the teaching process in detail.'}
    # ]
    # response = openai.ChatCompletion.create(
    #     model="gpt-3.5-turbo",
    #     messages=messages,
    # )
    # print("使用的tokens：", response.usage.total_tokens)
    #
    # full_lesson_plan = response.choices[0].message.content
    #
    # sections = {
    #     '教学目标': extract_section(full_lesson_plan, '教学目标'),
    #     '教学方法': extract_section(full_lesson_plan, '教学方法'),
    #     '教学重难点': extract_section(full_lesson_plan, '教学重难点'),
    #     '教学过程': extract_section(full_lesson_plan, '教学过程'),
    # }
    #
    # # 返回 JSON 结构的教案各部分
    # return jsonify(sections)


    # 初始化会话状态
    conversation = []

    # 创建教案部分的列表
    lesson_plan_parts = [
        # "Content Analysis",
        # "Student Analysis",
        "TeachingObjectives",
        "TeachingMethods",
        # "Key Points",
        # "Key Difficulties",
        # "Teaching Resource",
        # "Teaching Evaluation"
    ]

    # 逐步生成每个部分
    lesson_plan_sections = {}
    for index, part in enumerate(lesson_plan_parts):
        # 创建适应当前部分的提示
        if index == 0:
            # 第一部分的提示
            prompt = f"Now suppose you are an English teacher, you need to generate lesson plan content based on the following information."\
                     f"Firstly, please generate the {part} based on the following details. " \
                     f"The main knowledge to be taught in this class is: {main_knowledge}., Students age is from: {min_age} to {max_age}. " \
                     f"The duration of this class is: {class_hour_count}., Other requirements of the teacher: {other_requirements}, "\
                     f"Attention: Please start your answer with '{part}:'."
        else:
            # 后续部分的提示，包括上一部分的内容作为背景
            prompt = f"Now that we have generated the {lesson_plan_parts[index - 1]}, " \
                     f"please generate the {part} start with '{part}:'."

        conversation.append({'role': 'system', 'content': prompt})

        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=conversation
        )

        # 将新的回复添加到会话中
        conversation.append({'role': 'assistant', 'content': response.choices[0].message.content})

        # 保存生成的部分
        section_key = part  # 提取关键词作为字典的键
        lesson_plan_sections[section_key] = response.choices[0].message.content

        # 返回JSON格式的教案各部分
    return jsonify(lesson_plan_sections)

# def extract_section(text, section_title):
#     # 假设每个部分都是以标题开头，后跟具体内容
#     # 这里使用正则表达式查找以标题开头，后面跟着任何内容，直到下一个标题的模式
#     pattern = rf"{section_title}:(.*?)(?=\n\w+:|$)"
#     match = re.search(pattern, text, re.DOTALL)
#     if match:
#         return match.group(1).strip()
#     return ""

@lessonPlan_bp.route('/regenerate', methods=["POST"])
def regenerate_lessonPlan():

    # selected_sections = request.form.get('sections')
    main_knowledge = request.form.get('main_knowledge')
    min_age = request.form.get('min_age')
    max_age = request.form.get('max_age')
    class_hour_count = request.form.get('class_hour_count')
    other_requirements = request.form.get('other_requirements')

    # 教案的所有部分
    lesson_plan_parts = [
        # "Content Analysis",
        # "Student Analysis",
        "TeachingObjectives",
        "TeachingMethods",
        # "Key Points",
        # "Key Difficulties",
        # "Teaching Resource",
        # "Teaching Evaluation"
    ]

    notRegenerated_content = {
        'main_knowledge': main_knowledge,
        'min_age': min_age,
        'max_age': max_age,
        'class_hour_count': class_hour_count,
        'other_requirements': other_requirements
    }
    # 放最终结果
    result = {}

    for part in enumerate(lesson_plan_parts):
        if part in request.form:
            notRegenerated_content[part] = request.form.get(part)


    # 检查并处理字段
    if 'TeachingObjectives' not in request.form:
        print("#########1")
        TeachingObjectives = regenerate_content('TeachingObjectives', notRegenerated_content)
        result['TeachingObjectives'] = TeachingObjectives
    else:
        print("#########2")
        TeachingObjectives = request.form.get('TeachingObjectives')
        result['TeachingObjectives'] = TeachingObjectives


    if 'TeachingMethods' not in request.form:
        print("#########3")
        TeachingMethods = regenerate_content('TeachingMethods', notRegenerated_content)
        result['TeachingMethods'] = TeachingMethods
    else:
        print("#########4")
        TeachingMethods = request.form.get('TeachingMethods')
        result['TeachingMethods'] = TeachingMethods

    # print(regenerated_content)

    return jsonify(result)


def regenerate_content(key, data):

    """
    使用 GPT-3.5 生成指定键的内容。

    :param key: 要生成内容的键名
    :param data: 包含背景信息的字典
    :return: 由 GPT-3.5 生成的内容
    """

    try:
        print("##########regenerate!!!!!!!")
        messages = [{
            'role': 'system',
            'content': f"the {key} does not quite meet the teacher's requirements, so please regenerate it." \
                       f'And you need to generate it based on the information of the other existing parts of the lesson plan: \n'
            }]

        # 添加每个详细信息作为对话的一部分
        for k, v in data.items():
            messages.append({
                'role': 'user',
                'content': f'{k}: {v}'
            })

        # 添加生成请求的消息
        messages.append({
            'role': 'system',
            'content': f"\nNow please generate the {key} start with '{key}:'."
        })


        print(messages)
        # 发送请求给 GPT-3.5
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=messages,
            # max_tokens=150  # 根据需要调整最大令牌数量
        )

        print("OpenAI response:", response)  # 打印响应查看内容
        return response.choices[0].message.content

    except Exception as e:
        print(e)  # 打印错误信息
        return jsonify({"error": str(e)}), 500  # 返回错误信息

@lessonPlan_bp.route('/download', methods=["POST"])
def download_lessonPlan():
    # 从请求中获取数据
    payload = request.json

    doc = Document()

    # 在文档中添加标题
    doc.add_heading('Lesson Plan', 0)

    ignore_fields = ['other_requirements']

    if 'min_age' in payload and 'max_age' in payload:
        student_age = f"The student age is from {payload['min_age']} to {payload['max_age']}."
        doc.add_heading('Student Age:', level=1)
        doc.add_paragraph(student_age)

    for key, value in payload.items():
        if key not in ignore_fields:
            # 先把value都转成字符串格式
            if isinstance(value, int):
                value = str(value)

            # 移除内容中的重复标题
            content_title = f"{key}:"
            if content_title in value:
                content = value.replace(content_title, '').strip()
            else:
                content = value
            # 为每个部分添加一个一级标题
            doc.add_heading(key, level=1)
            # 将内容添加到文档中
            doc.add_paragraph(content)

    # 将文档保存到字节流中
    fake_file = io.BytesIO()
    doc.save(fake_file)
    fake_file.seek(0)

    # 发送文档回前端
    return send_file(fake_file, mimetype='application/vnd.openxmlformats-officedocument.wordprocessingml.document')

@lessonPlan_bp.route('/publish', methods=['POST'])
def publish_lessonPlan():
    # 应该在登录处获取id
    # session['user_id'] = user_id
    payload = request.json
    new_lesson_plan = LessonPlan(
        # user_id=session.get('user_id'),
        main_knowledge=payload['main_knowledge'],
        min_age=payload['min_age'],
        max_age=payload['max_age'],
        class_hour_count=payload['class_hour_count'],
        other_requirements=payload['other_requirements'],
        teaching_objectives=payload['TeachingObjectives'],
        teaching_methods=payload['TeachingMethods']
    )
    g.session.add(new_lesson_plan)
    g.session.commit()
    return jsonify({'message': 'Lesson plan published successfully'}), 200

@lessonPlan_bp.route('/latest', methods=['GET'])
def get_latest_lessonPlans():
    try:
        # 这里我们使用会话来获取最后两个添加的教案
        latest_lesson_plans = g.session.query(LessonPlan).order_by(LessonPlan.lp_id.desc()).limit(2).all()
        # 将教案对象转换为字典列表
        latest_lesson_plans_list = [{
            'id': plan.lp_id,
            'main_knowledge': plan.main_knowledge,
            'min_age': plan.min_age,
            'max_age': plan.max_age,
            'class_hour_count': plan.class_hour_count,
            'other_details': "Please click to read other details!"
        } for plan in latest_lesson_plans]
        return jsonify(latest_lesson_plans_list), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@lessonPlan_bp.route('/details/<int:plan_id>', methods=['GET'])
def get_lessonPlan_details(plan_id):
    try:
        # 使用会话查询数据库，获取指定ID的教案
        lesson_plan = g.session.query(LessonPlan).get(plan_id)

        # 如果教案不存在，返回404错误
        if lesson_plan is None:
            return jsonify({'message': 'Lesson plan not found'}), 404

        # 教案存在，构建一个包含教案详细信息的字典
        lesson_plan_details = {
            'id': lesson_plan.lp_id,
            'main_knowledge': lesson_plan.main_knowledge,
            'min_age': lesson_plan.min_age,
            'max_age': lesson_plan.max_age,
            'class_hour_count': lesson_plan.class_hour_count,
            'other_requirements': lesson_plan.other_requirements,
            'teaching_objectives': lesson_plan.teaching_objectives,
            'teaching_methods': lesson_plan.teaching_methods
        }

        # 返回教案详情
        return jsonify(lesson_plan_details), 200
    except Exception as e:
        # 如果遇到异常，返回错误信息
        return jsonify({'error': str(e)}), 500
